<?php

namespace App\Store\Controllers\Account;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Store\Models\Account\SiteStore;
use App\Common\Services\Store\Common as StoreCommon;
use Illuminate\Support\Facades\Validator;
use Maatwebsite\Excel\Facades\Excel;
use App\Common\Services\CommonExcelExport;

class StoreController extends Controller
{

    /**
     * 获取店铺详情
     */
    public function getinfo(Request $request)
    {
        $cp_id = StoreCommon::getCurrentAccountCompanyId($request);
        $storeid = intval(StoreCommon::getCurrentAccountStoreId($request));
        $info = SiteStore::with(['brandinfo'])->where(['id' => $storeid, 'cp_id' => $cp_id])->first();
        if (!$info) {
            return response()->json(['code' => '001', 'msg' => '未获取到店铺信息']);
        }
        if ($info->contract_end_at < (time() + 30 * 86400)) {
            $info->days = ceil(($info->contract_end_at - time()) / 86400);
        }

        return response()->json(['code' => '000', 'msg' => '获取成功', 'data' => ['info' => $info]]);
    }


    /**
     * 获取列表
     */
    public function getlist(Request $request)
    {
        $request->is_can_use=1;
        $list = SiteStore::getList($request);
        return response()->json(['code' => '000', 'msg' => '获取成功', 'data' => $list]);
    }

    public function doisopenaddedrecovery(Request $request)
    {
        $cp_id = StoreCommon::getCurrentAccountCompanyId($request);
        $storeid = intval($request->storeid);
        $info = SiteStore::where(['id' => $storeid, 'cp_id' => $cp_id])->first();
        if (!$info) {
            return response()->json(['code' => '001', 'msg' => '未获取到店铺信息']);
        }
        if ($info->is_open_added_recovery == 1) {
            $is_open_added_recovery = 2;
        } else {
            $is_open_added_recovery = 1;
        }
        SiteStore::where(['id' => $storeid, 'cp_id' => $cp_id])->update(['is_open_added_recovery' => $is_open_added_recovery]);
        return response()->json(['code' => '000', 'msg' => '操作成功']);
    }


    public function doexport(Request $request)
    { //isgetall=1;
        $list = SiteStore::getList($request)['list'];
        $exceldata = [];
        $storeNames = array_unique(array_map(function ($item) {
            return $item['store_name'];
        }, $list));

        $row = [
            ['store_name' => '门店列表'],
            ['store_name' => '所属门店：' . join(',', $storeNames)],
            [
                'store_name' => '门店名称',
                'company_name' => '所属公司',
                'address_area' => '归属区域',
                'contact_name' => '公司负责人',
                'contact_phone' => '负责人电话',
                'is_can_use' => '是否可用',
                'brand_name' => '门店品牌',
                'business_mem_name' => '业务员',
                'customer_service_name' => '客服',
                'soft_base_fee' => '软件费',
                'soft_year_fee' => '年费',
                'contract_at' => '合同签订日期',
                'contract_years' => '合同年限',
                'contract_end_at' => '合同到期日期',
                'create_at' => '创建时间',
                'update_at' => '修改时间',
                'audit_status' => '审核状态',
                'contract_audit_status' => '合同审核状态',
                'remark' => '备注',
            ]
        ];
        foreach ($list as $val) {
            $exceldata[] = [
                'store_name' => $val['store_name'],
                'company_name' => $val['companyinfo']['company_name'],
                'address_area' => $val['address_area'],
                'contact_name' => $val['companyinfo']['contact_name'] ?? '',
                'contact_phone' => $val['companyinfo']['contact_phone'] ?? '',
                'is_can_use' => $val['is_can_use'] == 1 ? '是' : '否',
                'brand_name' => isset($val['brandinfo']['brand_name']) ? $val['brandinfo']['brand_name'] : '--',
                'business_mem_name' => isset($val['businessmeminfo']['mem_name']) ? $val['businessmeminfo']['mem_name'] : '--',
                'customer_service_name' => isset($val['customerserviceinfo']['mem_name']) ? $val['customerserviceinfo']['mem_name'] : '--',
                'soft_base_fee' => $val['soft_base_fee'] / 100,
                'soft_year_fee' => $val['soft_year_fee'] / 100,
                'contract_at' => $val['contract_at'] > 0 ? date('Y-m-d', $val['contract_at']) : '--',
                'contract_years' => $val['contract_years'],
                'contract_end_at' => $val['contract_end_at'] > 0 ? date('Y-m-d', $val['contract_end_at']) : '--',
                'create_at' => date('Y-m-d H:i:s', $val['create_at']),
                'update_at' => date('Y-m-d H:i:s', $val['update_at']),
                'audit_status' => $val['audit_status'] == 2 ? '审核中' : ($val['audit_status'] == 3 ? '审核成功' : '审核取消'),
                'contract_audit_status' => $val['contract_audit_status'] == 1 ? '未提交审核' : ($val['contract_audit_status'] == 2 ? '审核中' : ($val['contract_audit_status'] == 3 ? '审核成功' : '审核取消')),
                'remark' => $val['remark'],
            ];
        }

        $filename = '门店信息导出_' . time() . '.xlsx';
        return Excel::download(new CommonExcelExport($row, $exceldata), $filename);
    }

    /**
     * 门店补充的信息更新
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     * @throws \Illuminate\Validation\ValidationException
     */
    public function storeSave(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'id' => 'required',
            'p_code' => 'sometimes',
            'c_code' => 'sometimes',
            'd_code' => 'sometimes',
            'address_area' => 'sometimes',
            'brand_url' => 'sometimes',
            'qrcode_url' => 'sometimes',
            'tracing_url' => 'sometimes',
            'contact_phone' => 'sometimes',
            'staff_name' => 'sometimes',
            'wx_number' => 'sometimes',

        ], [
            'id.required' => 'ID必填',
        ]);


        if ($validator->fails()) {
            $msg = $validator->errors()->first();
            return response()->json(['code' => '001', 'msg' => $msg]);
        }
        $params = $validator->validated();


        $store = SiteStore::query()
            ->where('id', $params['id'])
            ->where('is_del', 1)
            ->first();

        if (empty($store)) {
            return response()->json(['code' => '001', 'msg' => '门店数据不存在']);
        }

        $data['p_code'] = $params['p_code'] ?? '';
        $data['c_code'] = $params['c_code'] ?? '';
        $data['d_code'] = $params['d_code'] ?? '';
        $data['address_area'] = $params['address_area'] ?? '';
        $data['brand_url'] = $params['brand_url'] ?? '';
        $data['qrcode_url'] = $params['qrcode_url'] ?? '';
        $data['tracing_url'] = $params['tracing_url'] ?? '';
        $data['contact_phone'] = $params['contact_phone'] ?? '';
        $data['staff_name'] = $params['staff_name'] ?? '';
        $data['wx_number'] = $params['wx_number'] ?? '';

        SiteStore::query()
            ->where('id', $params['id'])
            ->update($data);
        return response()->json(['code' => '000', 'msg' => '保存成功']);
    }


    /**
     * 门店详情
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     * @throws \Illuminate\Validation\ValidationException
     */
    public function storeInfo(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'id' => 'required',

        ], [
            'id.required' => 'ID必填',
        ]);


        if ($validator->fails()) {
            $msg = $validator->errors()->first();
            return response()->json(['code' => '001', 'msg' => $msg]);
        }
        $params = $validator->validated();


        $store = SiteStore::query()
            ->where('id', $params['id'])
            ->where('is_del', 1)
            ->first();

        if (empty($store)) {
            return response()->json(['code' => '001', 'msg' => '门店数据不存在']);
        }


        $store = $store->toArray();


        return response()->json(['code' => '000', 'msg' => '保存成功', 'data' => $store]);
    }

    /**
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function getQrcode(Request $request)
    {
        $cp_id = StoreCommon::getCurrentAccountCompanyId($request);
        $storeid = intval(StoreCommon::getCurrentAccountStoreId($request));
        $info = SiteStore::query()
            ->when($storeid > 0, function ($query) use ($storeid) {
                $query->where('id', $storeid);
            })
            ->when($storeid == 0, function ($query) {
                $query->where('qrcode_url', '<>', '');
            })
            ->where('cp_id', $cp_id)
            ->OrderBy('id', 'desc')
            ->first();


        $info = empty($info) ? [] : $info->toArray();
        $data['qrcode_url'] = $info['qrcode_url'] ?? '';
        $data['qr_name'] = '二维码营销系统';
        return response()->json(['code' => '001', 'msg' => '获取成功', 'data' => $data]);

    }


}
